
package cn.airnan.dg.controller;

import cn.airnan.dg.configs.Global;
import cn.airnan.dg.entity.Player;
import cn.airnan.dg.entity.Room;
import cn.airnan.dg.service.PlayerService;
import cn.airnan.dg.service.RoomService;
import cn.airnan.dg.utils.CommonResponse;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

/**
 * 玩家相关接口
 */
@RestController
@RequestMapping("/api/player")
public class PlayerController {

    private static final Logger log = LoggerFactory.getLogger(PlayerController.class);
    @Resource
    private PlayerService service;

    /**
     * 获取玩家列表
     *
     * @return 玩家列表
     */
    @GetMapping("/list")
    public CommonResponse list() {
        try {
            return CommonResponse.success(service.getPlayers());
        } catch (Exception e) {
            return CommonResponse.error(e.getMessage());
        }
    }

    /**
     * 判断玩家是否还在
     *
     * @return true/false
     */
    @PostMapping("/isExist")
    public CommonResponse isExist(@RequestBody Player player) {
        try {
            return CommonResponse.success(Global.PLAYERS.containsKey(player.getId()));
        } catch (Exception e) {
            return CommonResponse.error(e.getMessage());
        }
    }

    /**
     * 创建玩家
     *
     * @return 玩家信息
     */
    @PostMapping("/create")
    public CommonResponse create(@RequestBody Player player) {
        try {
            if (service.canCreatePlayer(player.getId())) {
                var result = service.createPlayer(player);
                if (result != null) {
                    log.info("【创建玩家】名称:{}", player.getId());
                    return CommonResponse.success(result);
                } else {
                    return CommonResponse.error("创建玩家失败，请重试！");
                }
            } else {
                return CommonResponse.error("玩家名称已存在，换一个吧！");
            }
        } catch (Exception e) {
            return CommonResponse.error(e.getMessage());
        }
    }

}
